package com.lv.file.core.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lv.file.common.uitils.RestResult;
import com.lv.file.core.dto.RegisterDto;
import com.lv.file.core.entity.User;
import com.lv.file.core.service.UserService;
import com.lv.file.core.util.JWTUtil;
import com.lv.file.core.vo.LoginVo;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author BUG
 */
@RefreshScope   // 动态获取并刷新配置
@Slf4j
@RestController
@RequestMapping("/user")
@Tag(name = "user", description = "该接口为用户接口，主要做用户登录，注册和校验token")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    JWTUtil jwtUtil;

    @Value("${coupon.user.name}")
    private String name;
    @Value("${coupon.user.age}")
    private Integer age;
    /**
     * 成功响应测试
     */
    @GetMapping(value="/test1")
    @ResponseBody
    public RestResult test1(){
//        return RestResult.success();
        User user = new User();
        user.setUserName(name);
        return RestResult.success().data(user);
    }

    /**
     * 失败响应测试
     */
    @GetMapping(value="/test2")
    @ResponseBody
    public RestResult test2(){
        return RestResult.fail();
    }

    /**
     * 空指针异常响应测试
     */
    @GetMapping(value="/test3")
    @ResponseBody
    public RestResult test3(){
        String s = null;
        int i = s.length();
        return RestResult.success();
    }

    @Operation(summary = "用户注册", description = "注册账号", tags = {"user"})
    @PostMapping(value = "/register")
    @ResponseBody
    public RestResult<String> register(@RequestBody RegisterDto registerDto) {
        RestResult<String> restResult = null;
        User user = new User();
        user.setUserName(registerDto.getUserName());
        user.setTelephone(registerDto.getTelephone());
        user.setPassword(registerDto.getPassword());

        restResult = userService.registerUser(user);

        return restResult;
    }

    @Operation(summary = "用户登录", description = "用户登录认证后才能进入系统", tags = {"user"})
    @GetMapping(value = "/login")
    @ResponseBody
    public RestResult<LoginVo> userLogin(String telephone, String password) {
        RestResult<LoginVo> restResult = new RestResult<LoginVo>();
        LoginVo loginVo = new LoginVo();
        User user = new User();
        user.setTelephone(telephone);
        user.setPassword(password);
        RestResult<User> loginResult = userService.login(user);

        if (!loginResult.getSuccess()) {
            return RestResult.fail().message("登录失败！");
        }

        loginVo.setUserName(loginResult.getData().getUserName());
        String jwt = "";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            jwt = jwtUtil.createJWT(objectMapper.writeValueAsString(loginResult.getData()));
        } catch (Exception e) {
            return RestResult.fail().message("登录失败！");
        }
        loginVo.setToken(jwt);

        return RestResult.success().data(loginVo);
    }

    @Operation(summary = "检查用户登录信息", description = "验证token的有效性", tags = {"user"})
    @GetMapping("/checkuserlogininfo")
    @ResponseBody
    public RestResult<User> checkToken(@RequestHeader("token") String token) {
        RestResult<User> restResult = new RestResult<User>();
        User tokenUserInfo = null;
        try {

            Claims c = jwtUtil.parseJWT(token);
            String subject = c.getSubject();
            ObjectMapper objectMapper = new ObjectMapper();
            tokenUserInfo = objectMapper.readValue(subject, User.class);

        } catch (Exception e) {
            log.error("解码异常");
            return RestResult.fail().message("认证失败");

        }

        if (tokenUserInfo != null) {

            return RestResult.success().data(tokenUserInfo);

        } else {
            return RestResult.fail().message("用户暂未登录");
        }
    }
}